package com.tangruojie.handler;

import com.alibaba.fastjson2.JSON;
import com.tangruojie.domain.ResponseCode;
import com.tangruojie.domain.ResponseResult;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * URL 级错误处理器
 * 403（无权限）处理器：AccessDeniedHandler
 */
@Component
public class UnauthorizedHandler implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        response.setContentType("application/json");
        response.setCharacterEncoding("utf-8");
        ResponseResult responseResult = new ResponseResult(
                ResponseCode.UNAUTHORIZED,
                "无权限",
                null
        );
        response.getWriter().print(JSON.toJSONString(responseResult));
    }
}
